/**
 * Created by tianjie on 2017/12/6.
 */
$(function () {
    remain.init()
});

var remain = {
    URL : {
        getRemainData:function(){
            return "/admin/statistics/remainData";      //获取留存数据
        }
    },
    init:function(){
        common.initDateTimeRange();//  初始化时间控件
        var day = getNowFormatDate();
        var thirtyDay = minusThirtyDay();
        $('#dateTimeRange').val(thirtyDay+" 至 "+day);
        getData();  //请求后台数据 组装折线图
    }
};

/**
 * 清除时间
 */
function begin_end_time_clear() {
    $('#dateTimeRange').val('');
    $('#beginTime').val('');
    $('#endTime').val('');
}

/********************** 以下为折线图 *******************************/

var myChart = echarts.init(document.getElementById('main'),'macarons');
var colors = ['#5793f3', '#d14a61', '#675bba'];

var initChart = function(xData,secondData,seventhData,thirtiethData){
    Highcharts.chart('main', {
        chart: {
            type: 'line'
        },
        title: {
            text:null
        },
        tooltip: {
            shared: true,
            crosshairs: [{
                width: 1,
                dashStyle: 'Dot',
                color: 'green'
            }]
        },
        credits: {
            enabled: false
        },
        legend: {
            align: 'right',
            verticalAlign: 'top'
        },
        xAxis: [
            {
                categories: xData,
                tickInterval: 3,
                labels: {
                    format: '{value}',
                    style: {
                        color:'#008ACD'
                    }
                }
            }
        ],
        yAxis: {
            title: {
                text:null
            },
            labels: {
                style: {
                    color:'#008ACD'
                },
                formatter: function() {
                    return this.value +'%';
                }
            }
        },
        plotOptions: {
            spline: {
                marker: {
                    enabled:true,
                    radius: 0,
                    lineColor: '#D14A61',
                    fillColor:'#fff',
                    symbol: 'circle', //曲线点类型："circle", "square", "diamond", "triangle","triangle-down"，
                    lineWidth: 1
                }
            },
            line: {
                dataLabels: {
                    enabled: true          // 开启数据标签
                },
                enableMouseTracking: true // 关闭鼠标跟踪，对应的提示框、点击事件会失效
            }
        },
        series: [{
            name: '次日留存率',
            type: 'spline',
            data:secondData,
            color: '#7CB5EC',
            tooltip: {
                valueSuffix: '%'
            }
        }, {
            name: '7日留存率',
            type: 'spline',
            data:seventhData,
            color: '#8085E9',
            tooltip: {
                valueSuffix: '%'
            }
        }, {
            name: '30日留存率',
            type: 'spline',
            data:thirtiethData,
            color: '#8085E9',
            tooltip: {
                valueSuffix: '%'
            }
        }]
    });
};


function initRemainTable(data) {
    $("#demo-table").html("");
    var num = data.length;
    var str = "<thead><tr><th>日期</th><th>新增人数</th><th>次日留存率</th><th>7日留存率</th><th>30日留存率</th></tr>" +
        "</thead><tbody>";
    if(num > 0){
        $.each(data, function (i, n) {
            str += "<tr><td>"+data[num-1-i].date+"</td><td>"+data[num-1-i].addNum+"</td><td>"+data[num-1-i].secondDay +
                "</td><td>"+data[num-1-i].seventhDay+"</td><td>"+data[num-1-i].thirtiethDay+"</td></tr>";
        });
    }else {
        str += "<tr><td colspan='5'>没有找到匹配的记录</td></tr>"
    }
    $("#demo-table").append(str);
}

//请求后台数据
var getData = function(){
    var beginTime = $('#beginTime').val();
    var endTime = $('#endTime').val();
    var time = $('#dateTimeRange').val();
    /** 不知道怎么回事 首次进入页面点击今日时会出现beginTime endTime为空的情况 在这里特殊处理下 ***/
    if(beginTime==""||endTime==""){
        //2017-05-26 至 2017-05-26
        beginTime = time.substring(0,10);
        endTime = time.substring(13);
    }
    $.ajax({
        url : remain.URL.getRemainData(),
        type:'POST',
        async:true,    //或false,是否异步
        data:{
            beginTime:beginTime,endTime:endTime
        },
        timeout:5000,    //超时时间
        dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
        success:function(data,textStatus,jqXHR){
            console.log(data);
            if(data.code!=0){
                layer.msg(data.msg);
                return false;
            }
            initChartHead(data.data.avg);
            dataHandler(data.data.data);
        },
        error:function(xhr,textStatus){
            console.log('错误')
            console.log(xhr)
            console.log(textStatus)
        }
    })

};

function initChartHead(data) {
    $("#retained-note").html('');
    var str = "<span>次日留存率(AVG) : "+getPercent(data[0].secondAvg)+"</span><span>7日留存率(AVG) : "+
        getPercent(data[0].seventhAvg)+ "</span><span>30日留存率(AVG) : "+getPercent(data[0].thirtiethAvg)+"</span>";
    $("#retained-note").append(str);
}

function dataHandler(dataList) {
    var xData = [];
    var secondData = [];
    var seventhData = [];
    var thirtiethData = [];
    for(var i = 0; i < dataList.length; i++){
        xData[i] = formatSimpleTime(dataList[i].date);
        dataList[i].date = xData[i];

        secondData[i] = dataList[i].secondDay * 100;
        dataList[i].secondDay = getPercent(dataList[i].secondDay);

        seventhData[i] = dataList[i].seventhDay * 100;
        dataList[i].seventhDay = getPercent(dataList[i].seventhDay);

        thirtiethData[i] = dataList[i].thirtiethDay * 100;
        dataList[i].thirtiethDay = getPercent(dataList[i].thirtiethDay);
    }
    initChart(xData,secondData,seventhData,thirtiethData);
    initRemainTable(dataList);
}

window.onresize = function () {
    myChart.resize();
};